/**
 * Created by easy on 15/5/15.
 */
$(document).ready(function () {
    //初始化pullToRefresh
    pullToRefresh.init({
        loadingFunction: util.pullToRefresh
    });
    var setName = function (name) {
        return name.split(".")[0]
    };
    var getAjaxID = function (string) {
        if (string != undefined && string != null) {
            return string.split("#")[1]
        } else {
            return "";
        }
    };
    var getAjaxStatus = function (string) {
        if (string != undefined && string != null) {
            return string.split("#")[0]
        } else {
            return "";
        }

    };
    //初始化AbnormalDetailRactive
    vars.ractiveAbnormalDetail = new Ractive({
        el: "CONTAINER-abnormal-detail",
        template: "#TEMPLATE-abnormal-detail",
        data: {
            ractiveData: [], formatDate: function (time, format) {
                return mc.dealTime(parseInt(time), format);
            }, setName: setName, getAjaxID: getAjaxID, getAjaxStatus: getAjaxStatus
        }
    });
    //初始化AbnormalRemarkRactive
    vars.ractiveAbnormalRemark = new Ractive({
        el: "CONTAINER-abnormalRemark",
        template: "#TEMPLATE-abnormalRemark",
        data: {
            ractiveData: [], formatDate: function (time, format) {
                return mc.dealTime(parseInt(time), format);
            }, setName: setName, getAjaxID: getAjaxID, getAjaxStatus: getAjaxStatus
        }
    });
});
(function () {
    vars.currentPage = 1;
    vars.pageSize = 10;
    basic.deviceReady = function () {
        var params = mc.getParamsFromURL(window.location);
        vars.abnormalID = params.keyID;
        if (vars.abnormalID == "") {
            mc.alert("待更新到本地，请返回刷新重试！", mc.backToPrePage);
        } else {
            if (!vars.userInfo) {
                mc.getUserInfo(function (data) {
                    vars.userInfo = JSON.parse(data);
                })
            }
            util.getAbnormalDetail(function () {
                mc.showContent();
                util.syncAbnormalDetailData(function () {
                    util.getAbnormalDetail(function () {
                    })
                });
            });
            service.updateAbnormalRemarkUnreadMake(vars.abnormalID, function () {
            });
            service.updateAbnormalUnreadMake(vars.abnormalID, function () {
            });
        }
        document.addEventListener('ViewDidAppear', basic.ViewDidAppear, false);
    };
    basic.ViewDidAppear = function () {
        if (!vars.userInfo) {
            mc.getUserInfo(function (data) {
                vars.userInfo = JSON.parse(data);
            })
        }
        util.getAbnormalDetail(function () {
            mc.showContent();
            util.syncAbnormalDetailData(function () {
                util.getAbnormalDetail(function () {
                })
            });
        });
        service.updateAbnormalRemarkUnreadMake(vars.abnormalID, function () {
        });
        service.updateAbnormalUnreadMake(vars.abnormalID, function () {
        });
    };
    //下拉刷新（同步数据后 显示列表）
    util.pullToRefresh = function () {
        util.syncAbnormalDetailData(function () {
            util.getAbnormalDetail(pullToRefresh.reset);
        });
    };
    //同步异常表，订单表，备注表数据
    util.syncAbnormalDetailData = function (callback) {
        mc.syncData(["QC_ORDER", "QC_ABNORMAL", "QC_REMARK"], callback)
    };

    // 获取异常详情
    util.getAbnormalDetail = function (callback) {
        var getAbnormalDetailCallBack = function (data) {
            //alert(JSON.stringify(data))

            for (var i in data) {
                data[i].orderAttachment = data[i].orderAttachment != undefined && data[i].orderAttachment != null && data[i].orderAttachment != "null" ? JSON.parse(data[i].orderAttachment)[0] : null;
            }
            if (data.length > 0) {
                vars.orderID = data[0].orderID;
                vars.processName = data[0].processName;
                vars.ractiveAbnormalDetail.data.ractiveData = data;
            }
            vars.ractiveAbnormalDetail.update("ractiveData");
            common.showFirstOrderPhotos(data);
            common.showPhotos(data);
            common.changePhotosProgress();
            util.getAbnormalRemark();
            if (callback != undefined) {
                callback();
            }
        };
        service.getAbnormalDetailData(vars.abnormalID, getAbnormalDetailCallBack)
    };

    // 获取异常备注
    util.getAbnormalRemark = function (callback) {
        var getAbnormalRemarkCallBack = function (data) {
            //alert(JSON.stringify(data));
            if (data.length <= 0) {
                $(".remark-reply").hide();
            }else{
                $(".remark-reply").show();
            }
            vars.ractiveAbnormalRemark.data.ractiveData = data;
            vars.ractiveAbnormalRemark.update("ractiveData");
            common.changePhotosProgress();
            common.showPhotos(data);
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfAbnormalRemarksList
            };
            common.morePage(optionsForMorePage);

            service.updateAbnormalRemarkUnreadMake(vars.abnormalID, function () {
            });
            if (callback != undefined) {
                callback();
            }
        };
        var optionsForInitScrollList = {
            mode: "normal",
            scrollContainer: $("#content")
        };
        common.initScrollList(optionsForInitScrollList);
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize,
            abnormalID: vars.abnormalID
        };
        service.getAbnormalRemarkData(options, getAbnormalRemarkCallBack)
    }
    //获取异常备注列表分页
    util.paginationOfAbnormalRemarksList = function () {
        var paginationOfAbnormalRemarksListCallback = function (data) {
            //alert(JSON.stringify(data))
            vars.ractiveAbnormalRemark.data.ractiveData = $.merge(vars.ractiveAbnormalRemark.data.ractiveData, data);
            vars.ractiveAbnormalRemark.update("ractiveData");
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfAbnormalRemarksList
            };
            common.morePage(optionsForMorePage);
        };
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize,
            abnormalID: vars.abnormalID
        };
        //alert(JSON.stringify(options))
        service.getAbnormalRemarkData(options, paginationOfAbnormalRemarksListCallback)
    };

    // 编辑异常详情
    util.editAbnormalDetail = function () {
        // 将要修改的异常数据保存到临时存储
        mc.saveDataToLocalStorage("submitData", vars.ractiveAbnormalDetail.data.ractiveData[0], function (data) {
            mc.jump('submit.html?submitType=2&processName=' + vars.processName, '编辑异常', 'SubmitModal');
        }, "app");
    };
    // 新增异常备注
    util.addAbnormalRemark = function () {
        mc.jump('submit.html?submitType=3&type=2&objID=' + vars.abnormalID + '&processName=' + vars.processName, '添加异常备注', 'SubmitModal');
    };


    util.editAbnormalRemark = function (remarkID) {
        for (var i = 0; i < vars.ractiveAbnormalRemark.data.ractiveData.length; i++) {
            if (vars.ractiveAbnormalRemark.data.ractiveData[i].jsonPK == remarkID) {
                mc.saveDataToLocalStorage("submitData", vars.ractiveAbnormalRemark.data.ractiveData[i], function (data) {
                    mc.jump('submit.html?submitType=4&type=2&objID=' + vars.abnormalID + "&processName=" + vars.processName, '编辑异常备注', 'SubmitModal');
                }, "app");
            }
        }
    };

    // 回复备注
    util.replyRemark = function (toUserID, toUserName) {
        if (toUserID) {
            mc.jump('submit.html?submitType=8&type=3&objID=' + vars.abnormalID + '&processName=' + vars.processName + "&toUserID=" + toUserID + "&toUserName=" + toUserName, '回复 ' + toUserName, 'SubmitModal');
        } else {
            mc.jump('submit.html?submitType=8&type=3&objID=' + vars.abnormalID + '&processName=' + vars.processName, '回复异常', 'SubmitModal');
        }
    };
    vars.inTheSubmit = false;
    vars.submitPhotosArray = [];

    // 改变异常状态
    util.changeAbnormalDetailStatus = function (status) {
        var content = vars.ractiveAbnormalDetail.data.ractiveData.description;
        if (vars.inTheSubmit == false) {
            vars.inTheSubmit = true;
        } else {
            return false
        }
        var submitCallback = function (data) {
            if (data.result == true) {
                vars.inTheSubmit = false;
                util.getAbnormalDetail();
            }
        };
        var time = new Date().getTime();
        var requestData = {
            "keyID": vars.abnormalID,
            "status": status,
            "userID": vars.userInfo.userID
        };
        var extraData = {
            "person": vars.userInfo.username,
            "action": (status == "1" ? "重启" : "完成")  + "了一条异常",
            "content": [{"text": content}]
        };
        //提交前向主数据异常表 修改指定异常
        var SQLOfUpdateAbnormal = "UPDATE QC_ABNORMAL SET statusEdit = '" + (status == "0" ? "已完成" : "进行中") + "',status = '" + (status == "0" ? "已完成" : "进行中") + "',abnormalStatusStatus = ?, lastModifiedByUserLogin = '" + vars.userInfo.username + "'," +
            "lastUpdateTime='" + time + "' WHERE jsonPK = '" + vars.abnormalID + "';";

        //前向主数据动态表 插入一条到全部历史
        /*var SQLOfInsertAbnormalToDynamic = "INSERT INTO QC_DYNAMIC " +
         "(jsonPK, matchID, description, createdName,lastUpdateTime, attachment, type) VALUES" +
         " ('remark" + time + "', '" + vars.abnormalID + "', '" + content + "','" + vars.userInfo.username + "','" + time + "','" + JSON.stringify(vars.submitPhotosArray) + "',2 );";
         */
        //提交后修改异常状态
        var SQLOfChangeAbnormalStatus = "UPDATE QC_ABNORMAL SET abnormalStatusStatus = ? WHERE jsonPK = '" + vars.abnormalID + "';";

        //提交前后 修改订单表状态
        var SQLOfChangeOrderStatus = "UPDATE QC_ORDER SET abnormalStatus = CASE " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.orderID + "%' AND FCloudDataTransferState = 'uploading') > 0) THEN 'uploading' " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.orderID + "%' AND FCloudDataTransferState = 'failed') > 0) THEN 'failed' " +
            "ELSE 'success' END WHERE jsonPK = '" + vars.orderID + "';";

        //提交前后 提交后修改异常状态
        /*var SQLOfChangeAbnormalStatus = "UPDATE QC_ABNORMAL SET abnormalStatusStatus = CASE " +
         "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.abnormalID + "%' AND FCloudDataTransferState = 'uploading') > 0) THEN 'uploading' " +
         "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.abnormalID + "%' AND FCloudDataTransferState = 'failed') > 0) THEN 'failed' " +
         "ELSE 'success' END WHERE jsonPK = '" + vars.abnormalID + "';";*/

        //var SQLOfChangeOrderStatus = "UPDATE tab_Order SET remark_status = 'test1111' WHERE json_pk = '"+vars.orderID+"';";
        var params = {
            URL: service.url + "/changeAbnormalStatus",
            HTTPMethod: "post",
            requestData: requestData,
            extra: extraData,
            uploadAttachmentFilesInfo: vars.submitPhotosArray,
            matchIDs: vars.orderID + "," + vars.abnormalID,
            SQLOperation: {
                SQLOfAjaxStarted: SQLOfUpdateAbnormal + SQLOfChangeOrderStatus,
                SQLOfAjaxCompleted: SQLOfChangeAbnormalStatus + SQLOfChangeOrderStatus
            },
            noticePages: ["abnormal.html", "abnormal-detail.html", "orders.html", "dynamic.html"]
        };

        mc.submitToAjaxWorker(params, submitCallback)
    };
    util.showOrderPhotoByIndex = function (key) {
        common.showOrderPhotoByIndex(key, 1);
    };
    util.showDetailPhotosByIndex = function (obj, currIndex) {
        var data = vars.ractiveAbnormalDetail.data.ractiveData;
        common.showPhotosByIndex($(obj).parents(".photos-container").attr("value"), currIndex);
    };
    util.showRemarkPhotosByIndex = function (obj, currIndex) {
        var data = vars.ractiveAbnormalRemark.data.ractiveData;
        common.showPhotosByIndex($(obj).parents(".photos-container").attr("value"), currIndex);
    };
    util.showReplyRemarkPhotosByIndex = function (obj, currIndex) {
        common.showReplyPhotosByIndex($(obj).parents(".photos-container").attr("value"), currIndex);
    };

    // 提交开始时通知页面
    util.ajaxStarted = function (ajaxID, matchIDs) {
        var id = "abnormalCreate" + ajaxID;
        var obj = document.getElementById(id);
        if (obj) {
            var ajaxItem = $("#abnormalCreate" + ajaxID);
            common.changeAjaxBadgeStatus(1, ajaxItem, "abnormal", ajaxID);
        } else {
            util.changeAbnormalStatus(matchIDs);
        }

        var remarkId = "remarkCreate" + ajaxID;
        var remarkObj = document.getElementById(remarkId);
        if (remarkObj) {
            var ajaxItem = $("#remarkCreate" + ajaxID);
            common.changeAjaxBadgeStatus(1, ajaxItem, "abnormalRemark", ajaxID);
        } else {
            util.changeAbnormalRemarkStatus(matchIDs);
        }
        common.changePhotosProgress()
    };
    // 提交完成后通知页面
    util.ajaxCompleted = function (ajaxID, result, matchIDs) {
        var id = "abnormalCreate" + ajaxID;
        var obj = document.getElementById(id)
        if (obj) {
            var ajaxItem = $("#abnormalCreate" + ajaxID);
            if (result == "success") {
                common.changeAjaxBadgeStatus(2, ajaxItem, "abnormal", ajaxID, util.getAbnormalDetail);
            } else if (result == "failed") {
                common.changeAjaxBadgeStatus(3, ajaxItem, "abnormal", ajaxID);
            }
        } else {
            util.changeAbnormalStatus(matchIDs);
        }
        var remarkId = "remarkCreate" + ajaxID;
        var remarkObj = document.getElementById(remarkId);
        if (remarkObj) {
            var ajaxItem = $("#remarkCreate" + ajaxID);
            if (result == "success") {
                common.changeAjaxBadgeStatus(2, ajaxItem, "abnormalRemark", ajaxID, util.getAbnormalRemark);
            } else if (result == "failed") {
                common.changeAjaxBadgeStatus(3, ajaxItem, "abnormalRemark", ajaxID);
            }
        } else {
            util.changeAbnormalRemarkStatus(matchIDs);
        }
        common.changePhotosProgress();


        //var ajaxItem = $("#ajaxItem" + ajaxID) ? $("#ajaxItem" + ajaxID) : $("#ajaxItem" + matchIDs);
        /*if($("#remarkItem" + ajaxID) == undefined){
         var matchIDsArr = matchIDs.split(",");
         for (var i = 0; i < matchIDsArr.length; i++) {
         var remarkID = matchIDsArr[i];
         var remarkItem = $(document.getElementById('remarkItem' + remarkID));
         if (remarkItem != undefined) {
         remarkItem.find(".imgprogress").hide().html("");
         //alert(result)
         if (result == "success") {
         common.changeAjaxBadgeStatus(2, remarkItem, "abnormalRemark", ajaxID)
         } else if (result == "failed") {
         common.changeAjaxBadgeStatus(3, remarkItem, "abnormalRemark", ajaxID);
         }
         }
         }
         }else{
         var remarkItem = $(document.getElementById('remarkItem' + ajaxID));remarkItem.find(".imgprogress").hide().html("");
         //alert(result)
         if (result == "success") {
         common.changeAjaxBadgeStatus(2, remarkItem, "abnormalRemark", ajaxID)
         } else if (result == "failed") {
         common.changeAjaxBadgeStatus(3, remarkItem, "abnormalRemark", ajaxID);
         }
         }*/
    };

    // 根据提交的不同阶段改变页面的状态
    util.changeAbnormalStatus = function (matchIDs) {
        var matchIDsArr = matchIDs.split(",");
        for (var i = 0; i < matchIDsArr.length; i++) {
            var execFindStatus = function () {
                var abnormalID = matchIDsArr[i];
                var abnormalItem = $(document.getElementById(abnormalID));
                if (abnormalItem != undefined) {
                    var findAbnormalStatusCallback = function (data) {
                        //alert(JSON.stringify(data))
                        if(!data ||  data.length  == 0) {
                            return;
                        }
                        //var descriptionStatus = data[0].descriptionStatus ? data[0].descriptionStatus.split("#")[0] : "";
                        var abnormalStatusStatus = data[0].abnormalStatusStatus ? data[0].abnormalStatusStatus.split("#")[0] : "";
                        //var remarkStatus = data[0].remarkStatus ? data[0].remarkStatus.split("#")[0] : "";
                        //var attachmentStatus = data[0].attachmentStatus ? data[0].attachmentStatus.split("#")[0] : "";
                        //if (descriptionStatus == "uploading" || abnormalStatusStatus == "uploading" || remarkStatus == "uploading" || attachmentStatus == "uploading") {
                        if (abnormalStatusStatus == "uploading") {
                            common.changeAjaxBadgeStatus(1, abnormalItem, 'abnormal', abnormalID)
                        } else {
                            //if (descriptionStatus == "failed" || abnormalStatusStatus == "failed" || remarkStatus == "failed" || attachmentStatus == "failed") {
                            if (abnormalStatusStatus == "failed") {
                                common.changeAjaxBadgeStatus(3, abnormalItem, 'abnormal', abnormalID)
                            } else {
                                common.changeAjaxBadgeStatus(2, abnormalItem, 'abnormal', abnormalID, util.getAbnormalDetail)
                            }
                        }
                    };
                    var SQLOfFindOrderStatus = "SELECT abnormalStatusStatus FROM QC_ABNORMAL WHERE jsonPK = ?;";
                    mc.execSQL(SQLOfFindOrderStatus, [abnormalID], findAbnormalStatusCallback);
                }
            };
            execFindStatus();
        }
    };

    // 根据提交的不同阶段改变页面的状态
    util.changeAbnormalRemarkStatus = function (matchIDs) {
        var matchIDsArr = matchIDs.split(",");
        for (var i = 0; i < matchIDsArr.length; i++) {
            var execFindStatus = function () {
                var remarkID = matchIDsArr[i];
                var remarkItem = $(document.getElementById(remarkID));
                if (remarkItem != undefined) {
                    var findAbnormalRemarkStatusCallback = function (data) {
                        //alert(JSON.stringify(data))
                        var descriptionStatus = data[0].descriptionStatus ? data[0].descriptionStatus.split("#")[0] : "";
                        var attachmentStatus = data[0].attachmentStatus ? data[0].attachmentStatus.split("#")[0] : "";
                        if (descriptionStatus == "uploading" || attachmentStatus == "uploading") {
                            common.changeAjaxBadgeStatus(1, remarkItem, 'abnormal', remarkID)
                        } else {
                            if (descriptionStatus == "failed" || attachmentStatus == "failed") {
                                common.changeAjaxBadgeStatus(3, remarkItem, 'abnormal', remarkID)
                            } else {
                                common.changeAjaxBadgeStatus(2, remarkItem, 'abnormal', remarkID, util.getAbnormalRemark)
                            }
                        }
                    };
                    var SQLOfFindOrderStatus = "SELECT descriptionStatus,attachmentStatus FROM QC_REMARK WHERE jsonPK = ?;";
                    mc.execSQL(SQLOfFindOrderStatus, [remarkID], findAbnormalRemarkStatusCallback);
                }
            };
            execFindStatus();
        }
    };

    // 重新提交
    util.findThisAbnormalFailedTask = function (touchObj, abnormalID) {
        var sql = "SELECT FCloudDataTransferID FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + abnormalID + "%' AND FCloudDataTransferState = 'failed'";
        var findThisAbnormalsFailedTaskCallback = function (data) {
            //alert(JSON.stringify(data))
            for (var i = 0; i < data.length; i++) {
                data[i] = data[i].FCloudDataTransferID;
            }
            common.execUploadAjaxTask(touchObj, data);
        };
        mc.execSQL(sql, [], findThisAbnormalsFailedTaskCallback);
    };

})();